<?php
$userName = $_POST['username'];
$pw = $_POST['pw'];
$cpw = $_POST['cpw'];
$sex = $_POST['sex'];
$email = $_POST['email'];
$intro = $_POST['intro'];
$fav = implode(",",$_POST['fav']);
//进行数据验证
$errLog = 0; //错误标志位，默认为0，表示没有错误
$errMsg = '';
//判断用户名是否有填写
if($userName == ""){
    $errLog = 1;
    $errMsg .= '用户名必须填写！';
}
if($pw == "" || $cpw == ""){
    $errLog = 1;
    $errMsg .= '密码和确认密码必须填写！';
}
else{
    if($pw != $cpw){
        $errLog = 1;
        $errMsg .= '密码和确认密码必须相同！';
    }
    else{
        if(mb_strlen($pw,'UTF8') <= 4){
            $errLog = 1;
            $errMsg .= '密码长度不得小于5！';
        }
    }
}
if($errLog == "1"){
    echo "<script>alert('$errMsg');history.back();</script>";
    exit;
}
//接下来说明前端传过来的所有 数据均合法有效，可以写入数据库

include_once "conn.php";
//3、检查当前用户是否已经被占用
$sql = "select * from userinfo where username = '$userName'";
//4、执行sql查询
$result = mysqli_query($conn,$sql);


//5、处理查询结果
$num = mysqli_num_rows($result);
if($num){
    //说明$num等于1,即此用户名已经被占用
    echo "<script>alert('此用户名已经被占用');history.back();</script>";
    exit;
}
//接下来，说明用户名有效，可以写入数据库。
$sql = "insert into userinfo (username,pw,email,fav,intro,sex,upload_time) values ('$userName','" . md5($pw) . "','$email','$fav','$intro','$sex','" . time() . "')";
$result = mysqli_query($conn,$sql);
//错误调试方法
//1、打印SQL语句
//echo $sql;
//echo "<br>";
//2、打印 mysql错误信息
//echo mysqli_error($conn);
//exit;
if($result){
    echo "<script>alert('用户注册成功');location.href='login.html';</script>";
}
else{
    echo "<script>alert('用户注册失败');history.back();</script>";
}